#include "TcpClient.h"
#include "EventLoop.h"
#include "InetAddress.h"
#include "../base/logging.h"

#include <stdio.h>
#include <memory>

EventLoop* g_loop;

void connectCallback(int sockfd)
{
	printf("connected.\n");
	g_loop->quit();
}

std::string message = "Hello\n";

void onConnection(const TcpConnectionPtr& conn)
{
	if (conn->connected())
	{
		printf("onConnection(): new connection [%s] from %s\n",
			conn->name().c_str(),
			conn->peerAddress().toHostPort().c_str());
		conn->send(message);
		g_loop->quit();
	}
	else
	{
		printf("onConnection(): connection [%s] is down\n",
			conn->name().c_str());
	}
}

void onMessage(const TcpConnectionPtr& conn,
	Buffer* buf,
	Timestamp receiveTime)
{
	printf("onMessage(): received %zd bytes from connection [%s] at %s\n",
		buf->readableBytes(),
		conn->name().c_str(),
		receiveTime.toFormattedString().c_str());

	printf("onMessage(): [%s]\n", buf->retrieveAsString().c_str());
}

int main(int argc, char* argv[])
{
	Logger::setLogLevel(Logger::TRACE);
	EventLoop loop;
	g_loop = &loop;
	InetAddress addr("127.0.0.1", 1111);
	TcpClient client(g_loop, addr, "TestClient");

	client.setConnectionCallback(onConnection);
	client.setMessageCallback(onMessage);
	client.connect();
	loop.loop();
}